package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.squareup.picasso.Picasso;
import com.woyao.core.PayResult;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Demand;
import com.woyao.core.model.GetBalanceResponse;
import com.woyao.core.model.GetDemandResponse;
import com.woyao.core.model.GetMyMemberResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.MemberSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class DemandActivity extends AppCompatActivity  {

    private Integer id =0 ;

    private TextView memberTitle;
    private ImageView demand_image;
    private TextView title;
    private TextView relation;
    private TextView location;
    private TextView how;
    private TextView description;
    private EditText bidding;
    private EditText budgetText;
    private EditText chargeText;
    private LinearLayout actionArea;

    private Button demandVideoPlay;

    List<MemberSummary> members = new ArrayList<MemberSummary>();

    Spinner memberSpinner;
    private ArrayAdapter<String> memberAdapter;

    private String no;
    private String from = "";
    boolean changed = false;
    ProgressDialog progressDialog;
    private Demand demand = new Demand();
    private static final int SDK_PAY_FLAG = 1;

    Button nextBtn;


    Integer MEMBER_CODE  = 44 ;
    Integer RELATION_CODE  = 99 ;
    Integer INCLUDE_CODE  = 88 ;
    Integer HOW_CODE = 77;
    Integer TITLE_CODE =  66;
    Integer DESC_CODE =  55;
    Integer MEDIA_CODE =  7;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult result = new PayResult((Map<String, String>) msg.obj);

            String resultStatus = result.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(DemandActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                finishit();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(DemandActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                bidding.setText("0");
            }


        };
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demand_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        nextBtn = (Button) findViewById(R.id.demand_savenew);
        actionArea = (LinearLayout) findViewById(R.id.demand_actions);

        Intent intent = getIntent();

        from = intent.getStringExtra("from");



        how = (TextView)findViewById(R.id.id_how);

        demandVideoPlay  = (Button) findViewById(R.id.demand_video_play);


        memberTitle = (TextView)findViewById(R.id.demand_member);

        memberTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","demand");
                intent.setClass(DemandActivity.this, FilterMember.class);
                startActivityForResult(intent,MEMBER_CODE);
            }
        });

        bidding =(EditText)findViewById(R.id.id_biddingvalue);
        chargeText =(EditText)findViewById(R.id.id_charge);
        budgetText =(EditText)findViewById(R.id.id_budget);



        relation = (TextView)findViewById(R.id.action_filterrelation);
        location = (TextView)findViewById(R.id.action_filterlocation);


        how.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","demand");
                intent.setClass(DemandActivity.this, FilterHow.class);
                startActivityForResult(intent,HOW_CODE);
            }
        });

        demand_image = (ImageView) findViewById(R.id.id_demand_image);


        demand_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Open default camera

                Intent intent = new Intent();
                intent.putExtra( "demand", demand);
                intent.setClass( DemandActivity.this, DemandMediaActivity.class);
                startActivityForResult(intent ,MEDIA_CODE);

            }
        });

        title = (TextView)findViewById(R.id.id_demand_title);

        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","demandtitle");
                intent.putExtra( "content", title.getText() );
                intent.setClass(DemandActivity.this,  InputActivity.class);
                startActivityForResult(intent,TITLE_CODE);
            }
        });

        description = (TextView)findViewById(R.id.id_demand_description);

        description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type","demanddesc");
                intent.putExtra( "content", description.getText() );
                intent.setClass(DemandActivity.this,  InputActivity.class);
                startActivityForResult(intent,DESC_CODE);
            }
        });

        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","demand");
                KeyValueList kvl = new KeyValueList();
                kvl.setContent( demand.getInclude() );
                intent.putExtra("include", kvl  );
                intent.setClass(DemandActivity.this, FilterLocation.class);
                startActivityForResult(intent,INCLUDE_CODE);
            }
        });

        relation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("from","demand");
                KeyValueList kvl = new KeyValueList();
                kvl.setContent( demand.getRelation() );
                intent.putExtra("business", kvl  );
                intent.setClass(DemandActivity.this, FilterBusiness.class);
                startActivityForResult(intent,RELATION_CODE);
            }
        });

        TextView biddingExplan = (TextView)findViewById(R.id.id_biddingexplan);

        biddingExplan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("title","悬赏介绍");
                intent.putExtra("link", "http://www.woyaooo.com/charge.html");
                intent.setClass(DemandActivity.this, WebviewActivity.class);
                startActivity(intent);
            }
        });

        bidding.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    try {
                        String bidAmount = bidding.getText().toString();
                        float thevalue = Float.parseFloat(bidAmount);
                        Common.setDemandAttr(id,"bidding",bidAmount,"");
                        if (thevalue > 0) {
                            checkBalance();
                        }

                    } catch (Exception e) {
                        Toast.makeText(DemandActivity.this, "请输入合理的金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        });

        budgetText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    try {
                        String theAmount = budgetText.getText().toString();
                        float thevalue = Float.parseFloat(theAmount);
                        Common.setDemandAttr(id,"budget",theAmount);
                    } catch (Exception e) {
                        Toast.makeText(DemandActivity.this, "请输入合理的金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        });

        chargeText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    try {
                        String theAmount = chargeText.getText().toString();
                        float thevalue = Float.parseFloat(theAmount);
                        Common.setDemandAttr(id,"charge",theAmount);
                    } catch (Exception e) {
                        Toast.makeText(DemandActivity.this, "请输入合理的金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        });



        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( id ==0 ) {
                    saveIt();
                }else{
                    Intent intent = new Intent();
                    intent.putExtra("changed", changed);
                    setResult(666, intent);
                    finish();
                }

            }
        });

        Button demandMatch = (Button)findViewById(R.id.demand_match);
        demandMatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Common.setProfileAttr("demand_id", demand.getId() +"");
                Common.alert(DemandActivity.this,"已经设为主要需求");
                WoyaoooApplication.context = demand.getId();
//                Intent intent = new Intent();
//                intent.setClass( DemandActivity.this, ChanceActivity.class);
//                startActivity(intent);
//                finish();
            }
        });


        Button demandClose = (Button)findViewById(R.id.demand_close);
        demandClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Common.setDemandAttr(id,"available","0");
                Common.alert(DemandActivity.this,"已经关闭该业务需求");
                changed = true;
                Intent intent = new Intent();
                intent.putExtra("changed", changed );
                setResult(0, intent);
                finish();

            }
        });


        Button demandRecommend = (Button)findViewById(R.id.demand_recommend);
        demandRecommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass( DemandActivity.this, ReferActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });




        if (from != null && from.equals("register")) {
            this.setTitle("3/4. 说明合作需求");
            actionArea.setVisibility(View.GONE);
            nextBtn.setText("完成");
        }else{
            id = intent.getIntExtra("id", 0);
            if ( id >0){
                nextBtn.setText("完成");
            }else {
                this.setTitle("添加合作需求");
                nextBtn.setText("保存");
            }
        }


        if ( id ==0 ) {
            String howname = intent.getStringExtra("name");
            String howno = intent.getStringExtra("no");
            demand.setHow(howno);
            demand.setHow_names( howname);
            how.setText( howname);
            loadDefautMember( );
        }else{
            loadDemand( );
        }



    }



    private void appPay(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在启动支付······");
        progressDialog.show();

        final String payamount = bidding.getText().toString();
        AsyncTask<Void,Void,BaseResponse> task =new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.getOrder(WoyaoooApplication.userId,payamount );
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
                if (response.isSuccess()){
                    pay(response.getMessage());
                }
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }

    private void pay(final String orderInfo ){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(DemandActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo,true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private  void  finishit(){
        if ( from.equals( "register") ) {

            Intent intent = new Intent();
            intent.putExtra("from", "register");
            intent.setClass(DemandActivity.this, ChanceActivity.class);
            startActivity(intent);

        }else {

            Intent intent = new Intent();
            intent.putExtra("changed", changed);
            setResult(666, intent);
            finish();
        }
    }

    private void handleBalance( GetBalanceResponse response ){
        float bidAmount = Float.parseFloat(bidding.getText().toString());
        float currentMoney = Float.parseFloat(response.getMessage());
        if (currentMoney < bidAmount) {
            appPay();
//            Intent intent = new Intent();
////
//            intent.putExtra("money", Math.round(100 *(bidAmount - currentMoney )) /100.0);
//            intent.setClass(DemandActivity.this, MoneyActivity.class);
//            startActivity(intent);
        }



    }

    private void checkBalance(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在检查充值账户······");
        progressDialog.show();

        AsyncTask<Void,Void,GetBalanceResponse> task =new AsyncTask<Void, Void, GetBalanceResponse>() {
            @Override
            protected GetBalanceResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetBalanceResponse> responseCall = svc.getBalance(WoyaoooApplication.userId);
                try {
                    GetBalanceResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetBalanceResponse response) {
                progressDialog.dismiss();
                handleBalance(response);
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(666, intent);
        finish();
        return true;
    }

    private void saveIt( ) {


        if (title.getText().equals("")){
            Common.alert(DemandActivity.this,"请输入需求标题");
            return;
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<BaseResponse> responseCall = svc.addDemand(WoyaoooApplication.userId,demand.getMember_id(),demand.getHow(), demand.getImage(), demand.getTitle() , demand.getDescription(), Common.KeyValueToNos( demand.getInclude() ) , Common.KeyValueToNos( demand.getRelation() ) ,demand.getBudget(),demand.getCharge(),demand.getBidding());
                BaseResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null && response.isSuccess()) {

                    if (from.equals("register" ) ){
                        Intent intent = new Intent();
                        intent.putExtra( "title", demand.getTitle());
                        intent.putExtra( "id", demand.getId());
                        intent.setClass( DemandActivity.this, ReferActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        Intent intent = new Intent();
                        intent.putExtra("changed", true);
                        setResult(666, intent);
                        finish();
                    }

                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }


    private void loadDefautMember( ) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, GetMyMemberResponse> task = new AsyncTask<Void, Void, GetMyMemberResponse>() {
            @Override
            protected GetMyMemberResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<GetMyMemberResponse> responseCall = svc.getMyMember(WoyaoooApplication.userId);
                GetMyMemberResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final GetMyMemberResponse response) {
                if (response != null && response.getContent() != null) {

                    List<MemberSummary>  members  = response.getContent();

                    if (members.size() >0 ) {
                        for (MemberSummary me : response.getContent()) {
                            if (me.getStatus().equals("ongoing")) {
                                memberTitle.setText(me.getTitle());
                                demand.setMember_id(me.getId());
                                break;
                            }
                        }
                    }else{
                        memberTitle.setText("个人名义");
                        demand.setMember_id(0 );
                    }
                }
                progressDialog.dismiss();

            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }


    private void loadDemand( ) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetDemandResponse> task = new AsyncTask<Void, Void, GetDemandResponse>() {
            @Override
            protected GetDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<GetDemandResponse> responseCall = svc.getDemand(WoyaoooApplication.userId,id);
                GetDemandResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final GetDemandResponse response) {
                if (response != null && response.getContent() != null) {
                    renderDemand( response) ;
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }

    private boolean renderDemand(GetDemandResponse response) {
        progressDialog.dismiss();

        if (response == null) return false;
        demand = response.getContent();

        this.setTitle( demand.getTitle());

        Picasso.with(this)
                .load( demand.getImage())
                .into(demand_image );


        demandVideoPlay.setVisibility(View.GONE);


        memberTitle.setText( demand.getMember_title());
        title.setText( demand.getTitle() );

        boolean completed = true;

        how.setText(demand.getHow_names());

        if ( demand.getInclude().size() == 0 ) {
            completed = false;
            location.setText("不限");
        }else {
            location.setText( Common.KeyValueToNames( demand.getInclude() ));
        }

        if ( demand.getRelation().size() == 0 ) {
            completed = false;
            relation.setText("不限");
        }else {
            relation.setText( Common.KeyValueToNames( demand.getRelation() ));
        }

        bidding.setText( demand.getBidding() +"");
        budgetText.setText( demand.getBudget() +"");
        chargeText.setText( demand.getCharge() +"");

        description.setText(demand.getDescription());

        int index = 0;
        for ( MemberSummary  one : members){

            if (one.getId() == demand.getMember_id()){
                memberSpinner.setSelection( index);
                break;
            }
            index += 1;
        }

        return completed;

    }

    String picturePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == TITLE_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            demand.setTitle(con.toString());
            title.setText( con);
            changed = true;
            if (id > 0) {
                Common.setDemandAttr(id, "title", con.toString());
            }
        }else if(requestCode == DESC_CODE  && resultCode == 666 ) {
            CharSequence con = data.getCharSequenceExtra("content");
            if (con == null) return;
            demand.setDescription(con.toString());
            description.setText( con);
            changed = true;
            if (id > 0) {
                Common.setDemandAttr(id, "description", con.toString());
            }
        }else if(requestCode == INCLUDE_CODE && resultCode == 666){
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            location.setText(Common.KeyValueToNames( thelist.getContent()) );
            changed = true;
            if (id > 0) {
                Common.setDemandAttr(id, "include", Common.KeyValueToNos( thelist.getContent()));
            }
        }else if(requestCode == RELATION_CODE && resultCode == 666){
            KeyValueList thelist = (KeyValueList ) data.getExtras().get("result");

            demand.setRelation(thelist.getContent()  );
            relation.setText( Common.KeyValueToNames( thelist.getContent())  );
            changed = true;
            if (id > 0) Common.setDemandAttr(id,"relation",  Common.KeyValueToNos( thelist.getContent()) );
        }else if(requestCode == HOW_CODE &&resultCode ==666) {
            String howname = data.getStringExtra("name");
            String howno = data.getStringExtra("no");
            demand.setHow( howno);
            how.setText(howname);
            changed = true;
            if  (id > 0 ){
                Common.setDemandAttr(id, "how", howno);

            }
        }else if(requestCode == MEMBER_CODE && resultCode ==666) {
            Integer member_id = data.getIntExtra("member_id", 0);
            String member_title = data.getStringExtra("member_title");
            if  (id > 0 ){
                Common.setDemandAttr(id, "member_id", member_id +"");
            }
            changed = true;
            demand.setMember_id( member_id);
            memberTitle.setText( member_title );
        }else if(requestCode == MEDIA_CODE &&resultCode== Common.SUCCESS_CODE){
                loadDemand();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
